package net.neptech.service;

import com.alibaba.fastjson2.JSON;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import org.springframework.messaging.simp.stomp.*;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.messaging.WebSocketStompClient;

import java.util.Map;

@Service
@RequiredArgsConstructor
public class WebSocketClientService {

    private final WebSocketStompClient stompClient;
    private final String videoServiceWebSocketUrl;

    private StompSession session;

    /**
     * 连接到视频模块的 WebSocket 服务
     */
    @PostConstruct
    public void connect() {
        try {
            StompSessionHandler sessionHandler = new StompSessionHandlerAdapter() {
                @Override
                public void afterConnected(StompSession session, StompHeaders connectedHeaders) {
                    System.out.println("✅ AI 模块已连接到视频模块 WebSocket");
                    WebSocketClientService.this.session = session;
                }
            };

            stompClient.connectAsync(videoServiceWebSocketUrl, sessionHandler)
                    .whenComplete((session, throwable) -> {
                        if (throwable != null) {
                            System.err.println("❌ 连接视频模块 WebSocket 失败: " + throwable.getMessage());
                        }
                    });

        } catch (Exception e) {
            System.err.println("连接异常: " + e.getMessage());
        }
    }

    /**
     * 推送实时转录文本
     */
    public void pushRealTimeTranscript(String conferenceId, String text, boolean isPartial) {
        if (session == null || !session.isConnected()) {
            System.err.println("WebSocket 未连接，无法推送");
            return;
        }
        Map<String, Object> payload = Map.of(
                "type", "asr_update",
                "conferenceId", conferenceId,
                "text", text,
                "isPartial", isPartial,
                "from", "ai-bot"
        );
        try {
            StompHeaders headers = new StompHeaders();
            headers.setDestination("/app/send"); // 根据实际订阅路径设置
            session.send(headers, JSON.toJSONString(payload));
        } catch (Exception e) {
            System.err.println("推送失败: " + e.getMessage());
        }
    }


    /**
     * 推送 AI 会议纪要
     */
    public void pushMeetingSummary(String conferenceId, String summaryJson) {
        if (session == null || !session.isConnected()) {
            System.err.println("WebSocket 未连接，无法推送");
            return;
        }

        Map<String, Object> payload = Map.of(
                "type", "ai_summary",
                "conferenceId", conferenceId,
                "data", summaryJson
        );

        try {
            StompHeaders headers = new StompHeaders();
            headers.setDestination("/app/send"); // 根据实际订阅路径设置
            session.send(headers, JSON.toJSONString(payload));
        } catch (Exception e) {
            System.err.println("推送失败: " + e.getMessage());
        }
    }
}
